﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration.ConfigurationManager


Partial Class CarritoResumen
    Inherits System.Web.UI.Page

    'instancia de conexion
    Dim cn As New SqlConnection(ConnectionStrings("cn").ConnectionString)

    'funcion que retorne los celulares de la Session
    Private Function Listado() As DataTable
        Return CType(Session("carrito"), DataTable)
    End Function

    'funcion que retorne la suma de la columna monto
    Private Function Monto() As Double
        'si no tiene filas, retorno 0
        If Listado.Rows.Count = 0 Then
            Return 0
        Else
            'sino, retorno la suma de la columna monto
            Return Listado.Compute("Sum(monto)", "")
        End If
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Master.MostrarClienteSession()

        If Not Page.IsPostBack Then
            Dim dt As DataTable = Listado()
            GridView1.DataSource = dt
            GridView1.DataBind()

            If Listado.Rows.Count = 0 Then
                lblVacio.Visible = True
                ''MsgBox("SUPER VACIO")
                btnGoPaypal.Visible = False
                btnTransaccion.Visible = False
            Else
                btnGoPaypal.Visible = True
                btnTransaccion.Visible = True
            End If

            'el monto total
            txtMontoTotal.Text = Format(Monto(), "###,###,##0.00")
            'txtMontoTotal.Style("align") = "rigth"
            txtMontoTotal.Attributes.CssStyle.Add("TEXT-ALIGN", "right")
            txtCodCli.Text = Session("cliente")
        End If
    End Sub

    Protected Sub btnGoPaypal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGoPaypal.Click
        'Buscar Cliente
        Dim da As New SqlDataAdapter(
            "select * from tb_cliente where cod_cliente=@id", cn)
        da.SelectCommand.Parameters.Add("@id", SqlDbType.VarChar).Value = txtCodCli.Text
        Dim tb As New DataTable
        da.Fill(tb)
        'If tb.Rows.Count = 0 Then 'si no hay filas
        '    btnComprar.Enabled = False
        'Else
        '    btnComprar.Enabled = True
        '    'visualice el campo del nombre del cliente
        '    txtNombre.Text = tb.Rows(0)("nombrecia")
        If tb.Rows.Count = 0 Then 'si no hay filas
            MsgBox("No ha Iniciado Sesion, Por favor Logueese antes de comprar!")
            btnTransaccion.Enabled = False
        Else
            btnTransaccion.Enabled = True
            Response.Redirect("CPayPal.aspx?montototal=" + txtMontoTotal.Text)
        End If

        'If tb.Rows.Count = 1 Then
        '    Response.Redirect("CPayPal.aspx?montototal=" + txtMontoTotal.Text)
        'Else
        '    MsgBox("No ha Iniciado Sesion, Por favor Logueese antes de comprar!")
        '    btnTransaccion.Enabled = False
        'End If
    End Sub

    'Funcion que retorne el numero de pedido
    Private Function Autogenera() As Integer
        Dim n As Integer = 1, codOrd As Integer
        'comando
        Dim cmd As New SqlCommand("Select TOP 1 cod_orden from tb_orden_compra order by 1 desc", cn)
        cn.Open()               'abrir la conexion
        codOrd = cmd.ExecuteScalar  'retorna el valor
        cn.Close()              'cerrar conexion

        'Si NO esta vacio id, lo Incremento en 1
        If Not IsNothing(codOrd) Then
            n = codOrd + 1
        End If
        Return n
    End Function

    Protected Sub btnTransaccion_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnTransaccion.Click
        'Capturo el autogenerado
        Dim idp As Integer = Autogenera()

        cn.Open() 'abrir la conexion
        'DEFINIR LA TRANSACCION
        Dim tr As SqlTransaction = cn.BeginTransaction(IsolationLevel.Serializable)  'hasta q no termine los objetos estan bloqueados
        Try                                                                             'Se va bloquear la session carrito para este caso

            'comando
            Dim cmd As New SqlCommand(
                "Insert tb_orden_compra(cod_orden,cod_cliente,fecha_entrega,direccion_destino) Values(@codOrd,@codCli,@fec2,@direc)", cn, tr)
            With cmd.Parameters
                .Add("@codOrd", SqlDbType.Int).Value = idp
                .Add("@codCli", SqlDbType.VarChar).Value = txtCodCli.Text
                .Add("@fec2", SqlDbType.Date).Value = Request.Cookies("orden").Values("fecha_entrega")
                .Add("@direc", SqlDbType.VarChar).Value = Request.Cookies("orden").Values("direccion_destino")
            End With

            cmd.ExecuteNonQuery() 'ejecutar

            'Comando para el DETALLE:Session carrito
            For Each reg As DataRow In Listado.Rows

                'comando para insertar PedidoDeta
                cmd = New SqlCommand(
                    "Insert tb_detalle_orden_compra (cod_orden,cod_equipo,precio,cantidad,color,cod_operador) values(@codOrd,@codEqui,@pre,@cant,@color,@codOpe)", cn, tr)
                With cmd.Parameters
                    .Add("@codOrd", SqlDbType.Int).Value = idp
                    .Add("@codEqui", SqlDbType.Int).Value = reg("codEqui")
                    .Add("@pre", SqlDbType.Decimal).Value = reg("precio")
                    .Add("@cant", SqlDbType.Int).Value = reg("cantidad")
                    .Add("@color", SqlDbType.VarChar).Value = reg("color")
                    .Add("@codOpe", SqlDbType.Int).Value = reg("codOpe")
                End With

                cmd.ExecuteNonQuery()
            Next

            tr.Commit() 'Si esta todo OK, COMMIT
            MsgBox("Transacción exitosa!")
            Session("carrito").Clear()
            Response.Redirect("Catalogo.aspx")
        Catch ex As Exception
            MsgBox(ex.Message)
            tr.Rollback() 'Deshacer si hay errores
        Finally
            cn.Close()
        End Try
    End Sub

    
    Protected Sub cboMonedadPagar_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboMonedadPagar.SelectedIndexChanged

        If cboMonedadPagar.SelectedValue = "01" Then


            GridView1.DataSource = Listado()
            GridView1.DataBind()

            'For i As Integer = 0 To GridView1.Rows.Count - 1

            '    Dim soles As Double = CDbl(GridView1.Rows(i).Cells(5).Text.ToString)
            '    '    Dim cant As Double = CDbl(GridView1.Rows(i).Cells(6).Text.ToString)
            '    Dim soles2 As Double = CDbl(GridView1.Rows(i).Cells(7).Text.ToString)
            '    Dim PrecioDol As Double = soles * CDbl(Session.Item("Cambio"))
            '    Dim PrecioTotalDol As Double = soles2 * CDbl(Session.Item("Cambio"))


            '    GridView1.Rows(i).Cells(5).Text = Format(PrecioDol, "##,##0.00")
            '    GridView1.Rows(i).Cells(7).Text = Format(PrecioTotalDol, "##,##0.00")
            'Next

        Else



            For i As Integer = 0 To GridView1.Rows.Count - 1

                Dim soles As Double = CDbl(GridView1.Rows(i).Cells(4).Text.ToString)
                Dim cant As Double = CDbl(GridView1.Rows(i).Cells(5).Text.ToString)
                Dim soles2 As Double = CDbl(GridView1.Rows(i).Cells(6).Text.ToString)
                Dim PrecioDol As Double = soles / CDbl(Session.Item("Cambio"))
                Dim PrecioTotalDol As Double = soles2 / CDbl(Session.Item("Cambio"))


                GridView1.Rows(i).Cells(5).Text = Format(PrecioDol, "##,##0.00")
                GridView1.Rows(i).Cells(6).Text = Format(PrecioTotalDol, "##,##0.00")
            Next

        End If

    End Sub


End Class

